﻿using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        /// <summary>
        /// 服务器的公钥，用来给加密AES密钥
        /// </summary>
        const string RSA_PUBKEY = "AwEAAbQ5oCBWk/nOpt3yApBofZE5F4Wfv9KxnCO2hKxyUR3VshXPW1r2dOXFnRQGyAIKbt5F4SBUZ9n9kMDpvDScluic3M8zSQEi9Jiz/RzbNYvEw+4qBL2zrF1wG1daOyPfqtHjPgcDtyuYmBhVecTb226xhAjfEEE79x905BsC0Sw1";

        /// <summary>
        /// 客户端产生的AES密钥，客户端可以自由改变
        /// </summary>
        static string _aesKey = getAESKey();
        /// <summary>
        /// 用服务器的RSA公钥加密AES密钥
        /// </summary>
        static string _key = RSAHelper.Encrypt(_aesKey, RSA_PUBKEY);

        static void Main(string[] args)
        {
            //TODO，一些业务
            var model = new SaveModel() { Id = Guid.NewGuid().ToString(), Name = "Ttest", UpdateTime = DateTime.Now };

            var result = httpRequest<SaveModel, SaveModel>(model).Result;

            Console.WriteLine($"返回时间{result.UpdateTime}，提交时间{model.UpdateTime}");
            Console.ReadKey();
        }

        private static async Task<TResult> httpRequest<T,TResult>(T model)
        {
            //加密提交的对象
            var modelStr = Newtonsoft.Json.JsonConvert.SerializeObject(model);
            string modelStrEnc = AESHelper.Encrypt(modelStr, _aesKey);

            //请求接口
            var client = new HttpClient();
            //将AES密钥写入头部
            client.DefaultRequestHeaders.Add("key", _key);
            var msg = new HttpRequestMessage(HttpMethod.Put, "http://localhost:52679/api/default/save");
            msg.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(modelStrEnc));
            var resp = client.SendAsync(msg).Result;
            resp.EnsureSuccessStatusCode();
            var bytes = await resp.Content.ReadAsByteArrayAsync();
            var resultStrEnc = Encoding.UTF8.GetString(bytes);

            //用AES密钥解密数据
            var resultStr = AESHelper.Decrypt(resultStrEnc, _aesKey);
            var resultModel = Newtonsoft.Json.JsonConvert.DeserializeObject<TResult>(resultStr);
            return resultModel;
        }

        private static string getAESKey()
        {
            return "ae125efkk4454eeff444ferfkny6oxi8";
        }
    }

    public class SaveModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public DateTime UpdateTime { get; set; }
    }
}
